package com.hotchpotch.base;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.hotchpotch.R;
import com.hotchpotch.inter.PermissionListener;
import com.hotchpotch.util.StatusBarUtil;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by Administrator on 2017/5/11 0011.
 */
public abstract class BaseActivity extends AppCompatActivity {
    //获取布局文件ID
    protected abstract int getLayoutId();

    //布局加载
    protected abstract void initView();

    //监听事件
    protected abstract void initEvents();

    //数据
    protected abstract void initData();

    /**
     * 权限监听接口
     */
    private static PermissionListener perListener;
    /**
     * 是否全屏
     */
    private boolean isFullScreen = false;
    /**
     * 是否沉浸状态栏
     */
    private boolean isSteepStatusBar = false;
    protected BaseActivity mActivity;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        BarUtils.setColorNoTranslucent(this, getResources().getColor(R.color.colordf262c));
        ((MyApplication) this.getApplication()).getActivityManager().pushActivity(this);
        mActivity = this;
        setContentView(getLayoutId());
        setStatusBar();
        initView();
        initEvents();
        initData();
    }

    /**
     * 获取跳转界面时传递的数据
     *
     * @return
     */
    protected Bundle getIntentData() {
        Intent intent = getIntent();
        if (intent != null) {
            Bundle bundle = intent.getExtras();
            return bundle;
        }
        return null;
    }

    /**
     * 修改状态栏
     */
    protected void setStatusBar() {
        StatusBarUtil.setColorNoTranslucent(this, getResources().getColor(R.color.colordf262c));
    }

    /**
     * 设置是否全屏
     *
     * @param isFullScreen 是否全屏
     */
    public void setFullScreen(boolean isFullScreen) {
        this.isFullScreen = isFullScreen;
    }

    /**
     * 设置是否沉浸状态栏
     *
     * @param isSteepStatusBar 是否沉浸状态栏
     */
    public void setSteepStatusBar(boolean isSteepStatusBar) {
        this.isSteepStatusBar = isSteepStatusBar;
    }

    public void requestRunPermission(String[] permissions, PermissionListener listener) {
        Activity topActivity = ((MyApplication) this.getApplication()).getActivityManager().currentActivity();
        if (topActivity == null) {
            return;
        }
        perListener = listener;
        List<String> permissionList = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(topActivity, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(permission);
            }
        }

        if (!permissionList.isEmpty()) {
            //未获取
            ActivityCompat.requestPermissions(topActivity, permissionList.toArray(new String[permissionList.size()]), 1);
        } else {
            //获取了
            perListener.onGranted();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0) {
                    List<String> deniedList = new ArrayList<>();
                    for (int i = 0; i < grantResults.length; i++) {
                        int grantResult = grantResults[i];
                        String permission = permissions[i];
                        if (grantResult != PackageManager.PERMISSION_GRANTED) {
                            deniedList.add(permission);
                        }
                    }

                    if (deniedList.isEmpty()) {
                        perListener.onGranted();
                    } else {
                        perListener.onDenied(deniedList);
                    }
                }
                break;
        }
    }

    /**
     * 获取titlebar
     *
     * @return
     */
    /*protected RelativeLayout getTitleBar() {
        RelativeLayout layout = (RelativeLayout) findViewById(R.id.custom_titlebar_layout);
        return layout;
    }*/

    /**
     * 设置标题栏名称
     *
     * @param title
     * @return
     */
    /*protected TextView setTitleBatTitle(String title) {
        TextView textView = (TextView) findViewById(R.id.titlebar_title);
        if (textView != null) {
            textView.setText(title);
        }
        return textView;
    }*/

    /**
     * 标题栏返回监听
     */
    /*protected LinearLayout setBackClick() {
        LinearLayout layoutBack = (LinearLayout) findViewById(R.id.titlebar_back);
        return layoutBack;
    }*/


    /**
     * 标题栏购物车点击
     *
     * @return
     */
    /*protected RelativeLayout setCartClick() {
        RelativeLayout layoutCart = (RelativeLayout) findViewById(R.id.titlebar_cart);
        return layoutCart;
    }*/

    /**
     * 标题栏更多点击
     */
    /*protected RelativeLayout setMoreClick() {
        RelativeLayout layoutMore = (RelativeLayout) findViewById(R.id.titlebar_more);
        return layoutMore;
    }*/

    /**
     * 标题栏右边文字
     *
     * @return textview对象
     */
    /*protected TextView setRightTxt(String string) {
        TextView textView = (TextView) findViewById(R.id.titlebar_right_txt);
        textView.setVisibility(View.VISIBLE);
        if (!string.isEmpty()) {
            textView.setText(string);
        }
        return textView;
    }*/

    /**
     * activity跳转
     *
     * @param from
     * @param to
     * @param data 携带数据
     */
    protected void goToPage(Context from, Class<? extends Activity> to, Bundle data) {
        Intent i = new Intent();
        i.setClass(from, to);
        if (data != null) {
            i.putExtras(data);
        }
        from.startActivity(i);
    }

    /**
     * activity带结果跳转
     *
     * @param from
     * @param to
     * @param data
     * @param requestCode
     */
    protected void goToPageForResult(Context from, Class<? extends Activity> to, Bundle data, int requestCode) {
        Intent i = new Intent(from, to);
        if (data != null) {
            i.putExtras(data);
        }
        startActivityForResult(i, requestCode);
    }

    /**
     * 提示内容
     *
     * @param msg
     */
    protected void showToast(String msg) {
        if (!msg.isEmpty() && this != null) {
            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 显示 Snackbar（无action）
     * @param v
     * @param msg
     */
    protected void showSnackbar(View v, String msg) {
        Snackbar.make(v, msg, Snackbar.LENGTH_SHORT).show();
    }

    /**
     * 显示 Snackbar（有action）
     * @param v
     * @param msg
     * @param action
     */
    protected void showSnackbar(View v, String msg, String action) {
        Snackbar.make(v, msg, Snackbar.LENGTH_SHORT)
                .setAction(action, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                    }
                }).show();
    }

    /**
     * 关闭软键盘
     */
    protected void closeKeyboard() {
        View view = getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * 复制内容到系统剪贴板
     *
     * @param context
     * @param content
     */
    protected void copyToClipboard(Context context, String content) {
        //获取剪贴板管理器：
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        // 创建普通字符型ClipData
        ClipData mClipData = ClipData.newPlainText("copy", content);
        // 将ClipData内容放到系统剪贴板里。
        cm.setPrimaryClip(mClipData);
    }

    /**
     * 设置编辑框的焦点方法
     */
    protected void setEditTouch(EditText editText) {
        editText.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    v.setFocusableInTouchMode(true);
                    v.setFocusable(true);
                    v.requestFocus();
                }
                return false;
            }
        });
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    v.setFocusable(false);
                    v.setFocusableInTouchMode(false);
                }
                return false;
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ((MyApplication) this.getApplication()).getActivityManager().popActivity(this);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
    }
}
